package com.yun.baymax.activity.account;

import android.graphics.Typeface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.design.widget.TextInputLayout;
import android.support.v7.widget.AppCompatRadioButton;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.yun.baymax.R;
import com.yun.baymax.activity.BaseActivity;
import com.yun.baymax.bean.ChatUser;
import com.yun.baymax.bean.User;
import com.yun.baymax.cache.ChatUserCache;
import com.yun.baymax.cache.UserCache;
import com.yun.baymax.utils.DeviceUtils;
import com.yun.lib.utils.L;
import com.yun.lib.utils.NoUtilCheck;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobInstallation;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;


/**
 * @author Walking
 */
public class SignUpActivity extends BaseActivity {
    @BindView(R.id.register_tel)
    TextInputLayout registerTel;
    @BindView(R.id.register_verify_code)
    TextInputLayout registerVerifyCode;
    @BindView(R.id.register_verify_code_get)
    TextView registerVerifyCodeGet;
    @BindView(R.id.register_password)
    TextInputLayout registerPassword;
    @BindView(R.id.register_password_visible)
    ImageView registerPasswordVisible;
    @BindView(R.id.register_confirm)
    Button registerConfirm;
    @BindView(R.id.progress_bar_area)
    RelativeLayout progressBarArea;
    @BindView(R.id.rb_type1)
    AppCompatRadioButton rbType1;
    @BindView(R.id.rb_type2)
    AppCompatRadioButton rbType2;
    @BindView(R.id.rb_type3)
    AppCompatRadioButton rbType3;
    @BindView(R.id.rl_code)
    RelativeLayout rlCode;
    @BindView(R.id.rl_pwd)
    RelativeLayout rlPwd;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    boolean oldInput;
    boolean newInput;
    private CountDownTimer countDownTimer;

    @Override
    protected int setLayoutResourceId() {
        return R.layout.maccount_activity_register;
    }

    @Override
    protected void initVariables() {
        ButterKnife.bind(this);

        rbType1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    registerTel.getEditText().setText("");
                    rlCode.setVisibility(View.GONE);
                    rlPwd.setVisibility(View.VISIBLE);
                }

            }
        });
        rbType2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    registerTel.setHint("请输入手机号");
                    registerTel.getEditText().setText("");
                    rlCode.setVisibility(View.VISIBLE);
                    rlPwd.setVisibility(View.GONE);
                }

            }
        });

        rbType3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    registerTel.setHint("请输入用户名");
                    registerTel.getEditText().setText("");
                    rlCode.setVisibility(View.GONE);
                    rlPwd.setVisibility(View.VISIBLE);
                }

            }
        });

        rbType1.setChecked(true);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        registerTel.getEditText().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s)) {
                    oldInput = true;
                    if (newInput) {
                        registerConfirm.setSelected(true);
                        registerConfirm.setClickable(true);
                    }
                } else {
                    oldInput = false;
                    registerConfirm.setSelected(false);
                    registerConfirm.setClickable(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        registerPassword.getEditText().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s)) {
                    newInput = true;
                    if (oldInput) {
                        registerConfirm.setSelected(true);
                        registerConfirm.setClickable(true);
                    }
                } else {
                    newInput = false;
                    registerConfirm.setSelected(false);
                    registerConfirm.setClickable(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    @Override
    protected void loadData() {

    }


    @OnClick({R.id.register_verify_code_get, R.id.register_password_visible, R.id.register_confirm})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.register_verify_code_get:
                if (TextUtils.isEmpty(registerTel.getEditText().getText().toString().trim())) {
                    registerTel.setError(getString(R.string.fragment_login_tel_empty_error));
                    registerTel.requestFocus();
                } else if (!NoUtilCheck.isMobileNo(registerTel.getEditText().getText().toString())) {
                    registerTel.setError(getString(R.string.fragment_login_tel_invalid_error));
                    registerTel.requestFocus();
                } else {
                    registerTel.setErrorEnabled(false);
                    registerTel.setError("");
                    sendSms();
                }
                break;
            case R.id.register_password_visible:

                if (registerPassword.getEditText().getInputType() != InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
                    registerPasswordVisible.setImageResource(R.drawable.ic_eye_press);
                    registerPasswordVisible.setColorFilter(getResources().getColor(R.color.colorPrimary));
                    registerPassword.getEditText().setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    registerPasswordVisible.setImageResource(R.drawable.ic_eye);
                    registerPasswordVisible.clearColorFilter();
                    registerPassword.getEditText().setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                registerPassword.getEditText().setTypeface(Typeface.DEFAULT);
                registerPassword.getEditText().setSelection(registerPassword.getEditText().getText().length());

                break;
            case R.id.register_confirm:
                regist();
                break;
        }
    }

    private String getRegistPwd() {

        final String pwd = registerPassword.getEditText().getText().toString();
        if (TextUtils.isEmpty(pwd)) {
            registerPassword.setError(getString(R.string.fragment_login_password_empty_error));
            registerPassword.requestFocus();
        } else if (pwd.length() < 6 || pwd.length() > 20) {
            registerPassword.setError(getString(R.string.fragment_login_password_invalid_error));
            registerPassword.requestFocus();
        } else if (!NoUtilCheck.isReasonable(pwd) || NoUtilCheck.isNumeric(pwd) || NoUtilCheck.isCharacter(pwd)) {
            registerPassword.setError(getString(R.string.fragment_login_password_safe_error));
            registerPassword.requestFocus();
        } else {

            View view = getCurrentFocus();
            ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).
                    hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            progressBarArea.setVisibility(View.VISIBLE);

            registerPassword.setErrorEnabled(false);
            registerPassword.setError("");
            registerTel.setErrorEnabled(false);
            registerTel.setError("");
            return pwd;
        }
        return null;
    }


    private void regist() {

        final String tel = registerTel.getEditText().getText().toString();

        if (TextUtils.isEmpty(tel)) {
            registerTel.setError(getString(R.string.fragment_login_tel_empty_error));
            registerTel.requestFocus();
            return;
        }

        if (rbType1.isChecked()) {
            final String registPwd = getRegistPwd();
            if (registPwd != null) {
                final BmobUser bmobUser = new BmobUser();
                bmobUser.setUsername(tel);
                bmobUser.setPassword(registPwd);
                progressBarArea.setVisibility(View.VISIBLE);

                bmobUser.signUp(new SaveListener<BmobUser>() {
                    @Override
                    public void done(BmobUser bmobUser, BmobException e) {
                        if (e == null) {
                            String hxName = "bay" + registPwd + System.currentTimeMillis();
                            String hxPwd = "max" + registPwd;
                            showToast("注册成功");
                            updateUser(hxName, hxPwd);
                            registHx(bmobUser.getUsername(), hxName, hxPwd);
                            finish();
                        } else {
                            showToast(e.getMessage());
                        }
                    }

                    private void updateUser(String hxName, String hxPwd) {
                        User cu = BmobUser.getCurrentUser(User.class);
                        cu.setUserName(tel);
                        cu.setPsw(registPwd);
                        cu.setHxName(hxName);
                        cu.setHxPsw(hxPwd);
                        cu.setAndroidId(DeviceUtils.getAndroidId());
                        UserCache.getInstance().saveUser(cu);
                        updateUserInfo(cu.getObjectId());
                    }
                });

            }

        } else if (rbType2.isChecked()) {
            String code = registerVerifyCode.getEditText().getText().toString();

            if (!NoUtilCheck.isMobileNo(tel)) {
                registerTel.setError(getString(R.string.fragment_login_tel_invalid_error));
                registerTel.requestFocus();
            } else if (TextUtils.isEmpty(code)) {
                registerVerifyCode.setError(getString(R.string.fragment_login_password_code_empty_error));
                registerVerifyCode.requestFocus();
            } else {
                registerVerifyCode.setErrorEnabled(false);
                registerVerifyCode.setError("");
                registerTel.setErrorEnabled(false);
                registerTel.setError("");

                View view = getCurrentFocus();
                ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).
                        hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                progressBarArea.setVisibility(View.VISIBLE);
            }
        } else {
            String registPwd = getRegistPwd();
            if (registPwd != null) {
            }

        }
    }


    private void sendSms() {
        if (countDownTimer == null) {
            countDownTimer = new CountDownTimer(60000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    registerVerifyCodeGet.setEnabled(false);
                    registerVerifyCodeGet.setText(millisUntilFinished / 1000 + "s");
                }

                @Override
                public void onFinish() {
                    registerVerifyCodeGet.setEnabled(true);
                    registerVerifyCodeGet.setText(R.string.activity_register_get_verify_code);
                }
            };
        }
        countDownTimer.start();
        String tel = registerTel.getEditText().getText().toString();

    }

    /**
     * 注册环信
     */
    private void registHx(final String mianUserName, final String username, final String pwd) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    EMClient.getInstance().createAccount(username, pwd);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            loginHX(username, pwd);
                            // save current user
                            User user = UserCache.getInstance().getCurrentUser();
                            user.setHxName(username);
                            user.setHxPsw(pwd);
                            UserCache.getInstance().updateUser(user);

                            ChatUser chatUser = new ChatUser();
                            chatUser.setUsername(username);
                            chatUser.setPsw(pwd);
                            ChatUserCache.getInstance().saveChatUser(chatUser);
                            L.i("环信注册成功");
                        }
                    });
                } catch (final HyphenateException e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            int errorCode = e.getErrorCode();
                            if (errorCode == EMError.NETWORK_ERROR) {
                                Toast.makeText(getApplicationContext(), getResources().getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
                            } else if (errorCode == EMError.USER_ALREADY_EXIST) {
                                Toast.makeText(getApplicationContext(), getResources().getString(R.string.User_already_exists), Toast.LENGTH_SHORT).show();
                            } else if (errorCode == EMError.USER_AUTHENTICATION_FAILED) {
                                Toast.makeText(getApplicationContext(), "registration failed without permission", Toast.LENGTH_SHORT).show();
                            } else if (errorCode == EMError.USER_ILLEGAL_ARGUMENT) {
                                Toast.makeText(getApplicationContext(), getResources().getString(R.string.illegal_user_name), Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(getApplicationContext(), "Registration_failed", Toast.LENGTH_SHORT).show();
                                L.i(e.getMessage() + "----" + e.getDescription());
                            }
                        }
                    });
                }
            }
        }).start();
    }

    private void loginHX(final String username, final String pwd) {

        EMClient.getInstance().login(username, pwd, new EMCallBack() {

            @Override
            public void onSuccess() {
                L.i("hx-login" + username + "---" + pwd);
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String error) {
                L.i("hx-fail:" + username + "---" + pwd);
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(getApplicationContext(), "login failed", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    private void updateUserInfo(String objectId) {
        User localUser = UserCache.getInstance().getCurrentUser();
        String installationId = BmobInstallation.getInstallationId(this);
        localUser.setInstallationId(installationId);
        localUser.setEmail(null);
        localUser.update(objectId, new UpdateListener() {
            @Override
            public void done(BmobException e) {
            }
        });
    }
}
